import face_recognition
import cv2
import numpy as np
import OPi.GPIO as GPIO
import time

def motor():
  GPIO.setmode(GPIO.BOARD)

  in1 = 11
  in2 = 13
  in3 = 15
  in4 = 16

  # careful lowering this, at some point you run into the mechanical limitation

  step_sleep = 0.01


  step_count = 2048 # 5.625*(1/64) per step, 4096 steps is 360°

  direction = False # True for clockwise, False for counter-clockwise

   # defining stepper motor sequence (found in documentation http://www.4tronix.co.uk/arduino/Stepper-Motors.php)
  step_sequence = [[1,0,0,1],
                   [1,0,0,0],
                   [1,1,0,0],
                   [0,1,0,0],
                   [0,1,1,0],
                   [0,0,1,0],
                   [0,0,1,1],
                   [0,0,0,1]]

   # setting up
  GPIO.setmode( GPIO.BOARD )
  GPIO.setup( in1, GPIO.OUT )
  GPIO.setup( in2, GPIO.OUT )
  GPIO.setup( in3, GPIO.OUT )
  GPIO.setup( in4, GPIO.OUT )

   # initializing
  GPIO.output( in1, GPIO.LOW )
  GPIO.output( in2, GPIO.LOW )
  GPIO.output( in3, GPIO.LOW )
  GPIO.output( in4, GPIO.LOW )


  motor_pins = [in1,in2,in3,in4]
  motor_step_counter = 0 

  def cleanup():
            GPIO.output( in1, GPIO.LOW )
            GPIO.output( in2, GPIO.LOW )
            GPIO.output( in3, GPIO.LOW )
            GPIO.output( in4, GPIO.LOW )
            GPIO.cleanup()


  #the meat
  try:
         i = 0
         for i in range(step_count):
            for pin in range(0, len(motor_pins)):
                GPIO.output( motor_pins[pin], step_sequence[motor_step_counter][pin])
            if direction==True:

                motor_step_counter = (motor_step_counter - 1) % 8

            elif direction==False:

                motor_step_counter = (motor_step_counter + 1) % 8

            else: # defensive programming

                print( "uh oh... direction should *always* be either True or False" )

                cleanup()


                exit( 1 )

            time.sleep( step_sleep )

  except KeyboardInterrupt:
      cleanup()
      exit( 1 )

  cleanup()
  exit( 0 )






video_capture = cv2.VideoCapture(4)


tyt_image = face_recognition.load_image_file("tyt.jpg")
tyt_face_encoding = face_recognition.face_encodings(tyt_image)[0]




known_face_encodings = [
    tyt_face_encoding

]
known_face_names = [
    "tyt"

]

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_frame = frame[:, :, ::-1]

    # Find all the faces and face enqcodings in the frame of video
    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    # Loop through each face in this frame of video
    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        # See if the face is a match for the known face(s)
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)

        name = "Unknown"

        # If a match was found in known_face_encodings, just use the first one.
        # if True in matches:
        #     first_match_index = matches.index(True)
        #     name = known_face_names[first_match_index]

        # Or instead, use the known face with the smallest distance to the new face
        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]
            motor()
        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255),cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    # Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()